"""
config example:

[test_res_aaa]
cnt=2
0800-1400=1

[test_res_bbb]
cnt=3

[test_res_ccc.read]
cnt=10

[test_res_ccc.write]
cnt=1

"""

import cfg

import os
import time

def lock(res,job_name,job_date,cnt=1):
	for i in range(1,cnt+1):
		fn = job_name+'.'+job_date+'.'+str(i)
		res_path = os.path.join(cfg.res_root_dir,res,fn)
		open(res_path,'w')

def unlock(res,job_name,job_date):
	fn = job_name+'.'+job_date
	res_path = os.path.join(cfg.res_root_dir,res)
	for f in os.listdir(res_path):
		if f.find(fn)==0:
			os.remove(os.path.join(res_path,f))

def unlock_all(job_name,job_date):
	for res in os.listdir(cfg.res_root_dir):
		if os.path.isdir(os.path.join(cfg.res_root_dir,res)):
			p = os.path.join(cfg.res_root_dir,res)
			for r in os.listdir(p):
				if r.startswith(job_name+'.'+job_date+'.'):
					os.remove(os.path.join(p,r))

def clear(res):
	res_path = os.path.join(cfg.res_root_dir,res)
	for f in os.listdir(res_path):
		os.remove(os.path.join(res_path,f))

def locked(res):
	res_path = os.path.join(cfg.res_root_dir,res)
	return len(os.listdir(res_path))

def list(res):
	res_path = os.path.join(cfg.res_root_dir,res)
	return os.listdir(res_path)

def locked_oposite(res):
	root = res.split('.')[0]
	resources = os.listdir(cfg.res_root_dir)
	return sum([locked(r) for r in resources if r.split('.')[0]==root and r<>res])

def get_definitions():
	all = {}
	cp = cfg.ConfigParser()
	path = os.path.join(cfg.cfg_root_dir,'res.ini')
	cp.read(path)
	for s in cp.sections():
		all[s] = dict(cp.items(s))
	return all
	
def available(res,cnt=1):
	if locked_oposite(res):
		return False
	r_cfg = get_definitions().get(res,{})
	count = 0
	for s in r_cfg.keys():
		if s in ('cnt'):
			count = int(r_cfg[s])
			break	
	for s in r_cfg.keys():
		if '-' in s:
			start,stop = s.split('-')
			t = time.strftime("%H%M")
			if start <= t <= stop:
				count = int(r_cfg[s])
				break
	return locked(res)+cnt <= count

def create_all():
	all = get_definitions()
	for res in all.keys():
		path = os.path.join(cfg.res_root_dir,res)
		try:
			os.makedirs(path)
		except:
			pass

if __name__=="__main__":
	create_all()
	#print "server_conn", available('server_conn',2)
	#clear('test.read')
	#clear('test.write')	
	#print 'avail',available('test.read')
	#lock('test.read','jjj','20110831',3)
	#print locked('test.read')
	#print locked_oposite('test.read')
	#print locked_oposite('test.write')
	print get_definitions()
	print "avail", available('r1',2)
